package com.bihu.bihudemo.auth;

import com.bihu.bihudemo.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

//用户登录校验逻辑
@Service()
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    UserService userService;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //从Db中判断用户是否存在
        com.bihu.bihudemo.entity.User user = userService.getUserByUserName(s);
        if(user==null){
            throw new RuntimeException("用户不存在");
        }else {
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            System.out.println("获取权限");
            //从Db中加载用户权限
//            List<SysPermission> permissions = sysPermissionService.getPermissionByUid(user.getId());
//            permissions.forEach(sysPermission -> {
//                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
//                grantedAuthorities.add(grantedAuthority);
//            });

            //这里直接给角色吧
            grantedAuthorities.add(new SimpleGrantedAuthority("user"));

            //返回用户的信息,并将用户角色信息存入。
            return new User(user.getUsername(),user.getPassword(),true,true,true,true,grantedAuthorities);
        }


    }
}
